package com.qiall.boot.fileservice.impl;

import com.alibaba.fastjson.JSON;

import com.qiall.boot.fileservice.StreamProcessNotInServer;
import com.qiall.boot.fileservice.data.eitity.FileInfo;
import com.qiall.boot.fileservice.data.eitity.enums.FileSourceTypeEnum;
import com.qiall.boot.fileservice.data.eitity.enums.UploadStatusEnum;
import com.qiall.boot.fileservice.data.mapper.FileInfoMapper;
import com.qiall.boot.fileservice.impl.thirdrequest.BuyFilesResponse;

import com.qiall.uriutil.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * https://bayfiles.com/docs/api
 */
@Component("buyFilesService")
public class BuyFilesServiceImpl implements StreamProcessNotInServer {

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Override
    public String getDownLoadUrl(String fromId) {
        String url = "https://api.bayfiles.com/v2/file/id/info";
        url = url.replaceAll("id", fromId);
        return url;
    }

    @Override
    public void deleteFie(String fromId) {

    }

    public FileInfo buildFileInfo(String fromId) {
        String url = "https://api.bayfiles.com/v2/file/id/info";
        url = url.replaceAll("id", fromId);
        String response = HttpUtil.get(url);
        BuyFilesResponse.FileData fileData = JSON.parseObject(response, BuyFilesResponse.FileData.class);
        FileInfo fileInfo = new FileInfo();
        Integer maxId = fileInfoMapper.selectMaxId();
        Integer id = maxId == null ? 1 : maxId + 1;
        fileInfo.setId(id);
        fileInfo.setFileName(fileData.getData().getFile().getMetadata().getName());
        fileInfo.setContextType(null);
        fileInfo.setFileSize((long) fileData.getData().getFile().getMetadata().getSize().getBytes());
        fileInfo.setFromType(FileSourceTypeEnum.BAY_FILES.getCode());
        fileInfo.setUploadStatus(UploadStatusEnum.已上传.getCode());
        fileInfo.setFromId(fromId);
        return fileInfo;
    }
}
